package secondriver.heathfood.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import secondriver.heathfood.R;
import secondriver.heathfood.bean.FoodDetail;
import secondriver.heathfood.util.SimpleDiskCache;

import java.util.List;

/**
 * Author : secondriver
 */
public class FoodBriefListAdapter extends BaseAdapter {

    private final Context context;
    private final LayoutInflater inflater;
    private final List<FoodDetail> data;

    private SimpleDiskCache simpleDiskCache;

    public FoodBriefListAdapter(Context context, List<FoodDetail> foodDetailList) {
        this.context = context;
        this.inflater = LayoutInflater.from(this.context);
        this.data = foodDetailList;
    }

    public FoodBriefListAdapter(Context context, List<FoodDetail> foodDetailList, SimpleDiskCache simpleDiskCache) {
        this(context, foodDetailList);
        this.setSimpleDiskCache(simpleDiskCache);
    }

    public void setSimpleDiskCache(SimpleDiskCache simpleDiskCache) {
        if (simpleDiskCache != null) {
            this.simpleDiskCache = simpleDiskCache;
        }
    }

    @Override
    public int getCount() {
        return null != data ? data.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return null != data ? data.get(position) : FoodDetail.Null;
    }

    @Override
    public long getItemId(int position) {
        FoodDetail foodDetail = (FoodDetail) getItem(position);
        return foodDetail.getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder.FoodBriefViewHolder foodBriefViewHolder;
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.list_item_food_brief, parent, false);
            foodBriefViewHolder = new ViewHolder.FoodBriefViewHolder(convertView);
            convertView.setTag(foodBriefViewHolder);
        } else {
            foodBriefViewHolder = (ViewHolder.FoodBriefViewHolder) convertView.getTag();
        }
        final FoodDetail foodDetail = data.get(position);
        if (foodDetail != FoodDetail.Null) {
            foodBriefViewHolder.setContent(foodDetail, simpleDiskCache);
        }
        return convertView;
    }
}